# -*- coding: utf8 -*-
#
#https://yqfk.dgut.edu.cn 
#0 20 2-20/1 * * * * 触发周期建议使用这个 https://gitee.com/miranda0111/dgut_covid19/raw/master/index.py
#
#如需要配置多个账号请创建多个函数
#密码放在腾讯云上不用担心泄露
#
#所有教程均由ITCJL提供  =>  https://blog.csdn.net/qq_30243059
#https://blog.csdn.net/qq_30243059/article/details/116542476?spm=1001.2014.3001.5501
#
#本人只是搬运工，原GitHub的JS项目不再更新
##################################################################

import json
import requests
import re
import datetime
import json
import smtplib
from email.mime.text import MIMEText
from email.header import Header

mail_open=0 #0不开启邮件发送,1开启
user="" ##账号
password=""##密码
e_mail=" "#接收邮件的qq邮箱
mail_user = " "  # 用户名
mail_pass = " " ##授权码

def sendmail(rece_mail,text,user,title):
    if mail_open==0:
        return 0
    mail_host = "smtp.qq.com"  # 设置服务器
    sender = mail_user
    receivers = [rece_mail]  # 接收邮件，可设置为你的QQ邮箱或者其他邮箱
    message = MIMEText(text, 'plain', 'utf-8')
    message['From'] = Header("邮件代发", 'utf-8')
    message['To'] = Header(user, 'utf-8')
    subject = title
    message['Subject'] = Header(subject, 'utf-8')
    smtpObj = smtplib.SMTP_SSL(mail_host, 465)  # 发送服务器的端口号
    smtpObj.login(mail_user, mail_pass)
    smtpObj.sendmail(sender, receivers, message.as_string())


def work(user, password, mail):
    
    try:
        page = requests.get('https://cas.dgut.edu.cn/home/Oauth/getToken/appid/illnessProtectionHome/state/home.html')
        PHPSESSID = page.cookies["PHPSESSID"]
        token = re.findall(".*token = \"(.*)\";.*", page.text)[0]
        data = {"username": user,
                "password": password,
                "__token__": token,
                "wechat_verify": ""}
        PHPSESSID = "languageIndex=0; last_oauth_appid=xgxtt; PHPSESSID=" + PHPSESSID
        headers = {
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.198 Safari/537.36',
            'Host': 'cas.dgut.edu.cn',
            'Cookie': PHPSESSID
        }
        page = requests.post('https://cas.dgut.edu.cn/home/Oauth/getToken/appid/illnessProtectionHome/state/home.html',
                             data=data, headers=headers)
    
        submit_time = datetime.datetime.now().strftime('%Y-%m-%d')
        # 登录验证
        if (page.json()['message'] !='验证通过'):
            sendmail(mail,page.json()['message'],user,submit_time+":"+user+page.json()['message'])
            print(user + " : " + page.json()["message"])
            return " "
    
        successurl = page.json()['info'].replace("\\", "")
        page = requests.get(url=successurl)
        authorization = "Bearer " + re.findall(".*token=(.*)", page.url)[0]
    
        headers = {
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.198 Safari/537.36',
            "authorization": authorization,
            'Host':'yqfk.dgut.edu.cn',
            'Connection':'keep-alive',
            'Accept':'application/json',
            'Origin':'https://yqfk.dgut.edu.cn',
            'Content-Type':'application/json;charset=utf-8',
            'Sec-Fetch-Site':'same-origin',
            'Sec-Fetch-Mode':'cors',
            'Referer':'https://yqfk.dgut.edu.cn/main',
            'Accept-Encoding':'gzip,deflate,br',
            'Accept-Language':'zh-CN,zh;q=0.9',

        }
        page = requests.get(url="https://yqfk.dgut.edu.cn/home/base_info/getBaseInfo", headers=headers)
        form = page.json()['info']
        if(form['current_region']==[]):
            form.pop('current_region')
        if('whitelist' in form.keys()):
            form.pop('whitelist')
        if('latest_acid_test' in form.keys()):
            form.pop('latest_acid_test')
        if('acid_test_results' in form.keys()):
            form.pop('acid_test_results')

        form['confirm'] = 1
        form['submit_time'] = submit_time
        form = json.dumps(form)
        page = requests.post(url="https://yqfk.dgut.edu.cn/home/base_info/addBaseInfo", headers=headers, data=form)
        sendmail(mail, page.json()['message'], user,submit_time+":"+user+page.json()['message'])
        print(user + " : " + page.json()["message"] + ',邮件发送成功')
    except:
        print(user + " : " + page.text + ',邮件发送失败')
        sendmail(mail, page.text, user,submit_time+":"+user+page.text)

    return submit_time+":"+user+page.text


def main_handler(event, context):
    res=work(user,password,e_mail)
    return res
